package org.jradweb.core.orm;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;

public abstract class JModel implements Model {
	private static final Logger log=Logger.getLogger(JModel.class);
	public InvalidValue[] invaludValues=null;
	public String getErrorMessage(String propertyName){
		if(this.invaludValues==null) return null;
		for(InvalidValue iv:this.invaludValues){
			if(iv.getPropertyName().equals(propertyName))
			{
				return iv.getMessage();
			}
		}
		return null;
	}
	public Map<String,String> getErrorMessages(){
		Map<String,String> messages=new HashMap<String,String>();
		if(this.invaludValues==null)
			return messages;
		
		for(InvalidValue iv:this.invaludValues){
			messages.put(iv.getPropertyName(), iv.getMessage());
		}
		return messages;
	}
	
	public boolean hasErrors(Locale locale){
		InvalidValue[] ivs=this.getInvalidValues(locale);
		return ivs.length>0?true:false;
	}
	
	/**
	 * get invalid values
	 * @param locale
	 * @return
	 */
	public InvalidValue[] getInvalidValues(Locale locale){
		
		if(this.invaludValues!=null) return this.invaludValues;
		
		if(locale==null){
			locale=Locale.getDefault();
		}
		java.util.ResourceBundle rb=null;
		try {
			try {
				ClassLoader cl=Thread.currentThread().getContextClassLoader();
			} catch (RuntimeException e) {
				throw new MissingResourceException("No context classloader", null, "ValidatorMessages");
			}
			ResourceBundle.getBundle("ValidatorMessages",locale,Thread.currentThread().getContextClassLoader());
		} catch (MissingResourceException e) {
			log.debug("ResourceBundle ValidatorMessages not found in thread context classloader, use hibernate DefaultVlidatarMessages");
		}
		ClassValidator cv=new ClassValidator(this.getClass(),rb);
		this.invaludValues= cv.getInvalidValues(this);
		return this.invaludValues;
	}


}
